<template>
  <div class="contractAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave()"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 账期结算收款 -->
      <el-collapse-item
        name="1"
        style="position: relative"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">基本信息</span>
        </template>
        <div class="contract-info">
          <el-form
            :model="contactForm"
            ref="contactFormRef"
            :rules="queryContactRules"
            label-width="120px"
            v-enterToNext
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="选择部门：" prop="deptId">
                  <el-select
                    v-model="contactForm.deptId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleDepart"
                  >
                    <el-option
                      v-for="dict in deptList"
                      :key="dict.deptId"
                      :label="dict.deptName"
                      :value="dict.deptId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="巡检负责人员：" prop="allotRelList">
                  <el-select
                    style="height: 101%"
                    v-model="contactForm.allotRelList"
                    class="search-input"
                    placeholder="请选择"
                    clearable
                    multiple
                    value-key="userId"
                  >
                    <el-option key="0" label="" value="" disabled>
                      <span style="float: left; color: #8492a6">人员姓名</span>
                      <span style="margin: 0 80px 0 50px; color: #8492a6"
                        >联系方式</span
                      >
                      <span
                        style="
                          margin: 0 100px 0 0px;
                          color: #8492a6;
                          font-size: 13px;
                        "
                        >职位</span
                      >
                      <span style="color: #8492a6; font-size: 13px">部门</span>
                    </el-option>
                    <el-option
                      v-for="item in userList"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item"
                    >
                      <span
                        style="display: inline-block; width: 80px; float: left"
                        >{{ item.nickName }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          margin: 0 15px 0 23px;
                          color: #8492a6;
                          white-space: nowrap;
                          overflow: hidden;
                          text-overflow: ellipsis;
                        "
                        >{{ item.phonenumber ? item.phonenumber : "--" }}</span
                      >
                      <span
                        style="
                          display: inline-block;
                          width: 125px;
                          font-size: 13px;
                          margin: 0 0px 0 0px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.postName ? item.postName : "--" }}
                      </span>
                      <span
                        style="
                          display: inline-block;
                          margin: 0 0px 0 0px;
                          font-size: 13px;
                          transform: translateY(-11px);
                          color: #8492a6;
                        "
                      >
                        {{ item.fullDeptName ? item.fullDeptName : "--" }}
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="巡检日期：" prop="inspectionDates">
                  <el-date-picker
                    v-model="contactForm.inspectionDates"
                    format="YYYY/MM/DD"
                    class="search-input"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="巡检任务：" prop="patrolScheme">
                  <el-input
                    style="width: 268px"
                    v-model="contactForm.patrolScheme"
                    placeholder="请输入"
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 实收账期信息 -->
      <el-collapse-item
        name="2"
        style="position: relative"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">巡检日期明细</span>
          <div
            class="nofixed-search-button button-position"
            v-if="pageType !== 'detail'"
          >
            <el-button
              class="btn add"
              @click.stop="handleContactAdd(contactFormRef)"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
          </div>
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="contractForm.patrolSchemeAddInfoVos"
            border
            :height="'100%'"
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <!-- 操作模式 -->
            <el-table-column
              label="操作"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
              v-if="pageType !== 'detail'"
            >
              <!-- v-if="!operateType" -->
              <template #default="{ row, $index }">
                <div class="table-operate">
                  <img
                    src="@/assets/icons/images/edit.png"
                    class="table-icon"
                    title="编辑"
                    @click="handleOperate('edit', row, $index)"
                  />
                  <img
                    src="@/assets/icons/images/delete.png"
                    class="table-icon"
                    title="删除"
                    @click="handleOperate('delete', row, $index)"
                  />
                </div> </template
            ></el-table-column>
            <el-table-column
              label="巡检负责人员"
              prop="userId"
              :show-overflow-tooltip="true"
              min-width="160"
            >
              <template #default="{ row, $index }">
                <span
                  v-for="(item, index) in row.allotRelList"
                  :key="item.userId"
                  >{{ item.nickName
                  }}<span v-if="index + 1 !== row.allotRelList.length"
                    >，</span
                  ></span
                >
              </template>
            </el-table-column>
            <el-table-column
              label="巡检日期"
              prop="inspectionDates"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="巡检任务"
              prop="patrolScheme"
              :show-overflow-tooltip="true"
              min-width="160"
            />
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import { getUserListApi } from "@/api/operation/work";
import { getDeptListApi } from "@/api/information/customer";
import {
  pollingAddApi,
  pollingEditApi,
  getPollingApi,
} from "@/api/operation/project";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
const emit = defineEmits([
  // 回款新增组件显隐
  "followAddShow",
  // 更新回款组件显隐
  "update:followAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("");
//  详情加载效果
const detailInfoShow = ref(false);
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 下拉框引用
const refSelect = ref();
// 项目id
const projectId = ref(null);
//是否编辑
const editFlag = ref(false);
// 合同表单模板
const contractFormTemplate = {
  patrolSchemeAddInfoVos: [],
};
// 巡检删除列表(后端所需)
const deleteList = ref([]);
const data = reactive({
  //合同表单
  contractForm: JSON.parse(JSON.stringify(contractFormTemplate)),
  // 联系人表单
  contactForm: {
    allotRelList: [],
    inspectionDates: "",
    patrolScheme: "",
    projectId: null,
    deptId: null,
  },
  // 校验规则
  queryContactRules: {
    deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
    allotRelList: [
      { required: true, message: "请选择巡检负责人员", trigger: "change" },
    ],
    inspectionDates: [
      { required: true, message: "请选择巡检日期", trigger: "change" },
    ],
    patrolScheme: [
      { required: true, message: "请输入巡检任务", trigger: "blur" },
    ],
  },
  // 账期列表
  paymentDaysList: [],
  // 用户列表
  userList: [],
  // 部门列表
  deptList: [],
  // 项目列表
  projectList: [],
  // 是否列表
  flagList: [
    {
      label: "是",
      value: 0,
    },
    {
      label: "否",
      value: 1,
    },
  ],
});
const {
  contractForm,
  contactForm,
  queryContactRules,
  paymentDaysList,
  userList,
  deptList,
  projectList,
  flagList,
} = toRefs(data);
const contactAddShow = ref(false);

/**
 * @description: 保存
 */
const handleAddSave = async () => {
  if (!contractForm.value.patrolSchemeAddInfoVos.length) {
    return ElMessage.warning("请添加巡检日期明细！");
  }
  ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      let res;
      if (!editFlag) {
        res = await pollingAddApi(contractForm.value);
      } else {
        const obj = {
          deletePatrolSchemeAddInfoVos: deleteList.value,
          patrolSchemeAddInfoVos: contractForm.value.patrolSchemeAddInfoVos,
        };
        res = await pollingEditApi(obj);
      }

      if (res.code === 200) {
        emit("update:followAddShow", false);
        emit("refreshList", false);
        ElMessage.success(res.msg);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("update:followAddShow", false);
    contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:followAddShow", false);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid, fields) => {
    if (valid) {
      let userFlag;
      let timeFlag;
      contractForm.value.patrolSchemeAddInfoVos.some((item) => {
        userFlag = false;
        timeFlag = false;
        // 检测有没有相同负责人员
        contactForm.value.allotRelList.forEach((childItem) => {
          item.allotRelList.forEach((graItem) => {
            if (childItem.userId === graItem.userId) {
              userFlag = true;
            }
          });
        });
        // 检测有没有相同日期
        if (item.inspectionDates == contactForm.value.inspectionDates) {
          timeFlag = true;
        }
        if (userFlag && timeFlag) {
          return true; // 跳出循环
        }
      });
      //  && contactForm.value.patrolSchemeId
      if (userFlag && timeFlag) {
        return ElMessage.warning("该人员在此日期已有任务！");
      }

      if (operateType.value === "edit") {
        contractForm.value.patrolSchemeAddInfoVos[tableIndex.value] =
          JSON.parse(JSON.stringify(contactForm.value));
      } else {
        contractForm.value.patrolSchemeAddInfoVos.push({
          ...JSON.parse(JSON.stringify(contactForm.value)),
          projectId: projectId.value,
        });
      }
      contactForm.value = {};
      contactFormRef.resetFields();
      nextTick(() => {
        refSelect.value.focus();
      });
      operateType.value = "add";
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 处理销售清单表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = JSON.parse(JSON.stringify(row));
    contactAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refSelect.value.focus();
    });
  } else {
    deleteList.value.push(JSON.parse(JSON.stringify(row)));
    contractForm.value.patrolSchemeAddInfoVos.splice(tabIndex, 1);
  }
};
/**
 * @description: 处理部门选择
 * @param {Number} value 当前值
 */
const handleDepart = async (value, flag = true) => {
  if (flag) {
    contactForm.value.allotRelList = [];
  }
  if (value) {
    const selectDept = deptList.value.find((dept) => dept.deptId === value);
    // 打印所选部门信息
    console.log(selectDept);
    if (selectDept) {
      await getUserListApi(selectDept.deptType).then((res) => {
        if (res) {
          userList.value = res;
        }
      });
    } else {
      userList.value = [];
    }
  } else {
    userList.value = [];
  }
};
/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  projectId.value = id;
  try {
    detailInfoShow.value = true;
    const res = await getPollingApi(id);
    if (res.length) {
      editFlag.value = true;
    }
    contractForm.value.patrolSchemeAddInfoVos = res;
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("erp_account_period").then((res) => {
    if (res.code === 200) {
      paymentDaysList.value = res.data;
    }
  });
  await getDeptListApi().then((res) => {
    if (res.code === 200) {
      deptList.value = res.data;
    }
  });
  // await getUserListApi(2).then((res) => {
  //   if (res) {
  //     userList.value = res;
  //   }
  // });
}

onMounted(() => {
  getDicts();
  nextTick(() => {
    refSelect.value.focus();
  });
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.contractAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  // :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
  //   width: 268px !important;
  //   height: 34px !important;
  // }

  // .search-input {
  //   width: 268px;
  //   height: 34px;
  // }
  .contract-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }
  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
  //   :deep(.el-select) {
  //     width: 100%;
  //     // min-height: 50px !important;
  //     height: 100% !important;
  //     .el-input__wrapper {
  //       // min-height: 50px !important;
  //       height: inherit !important;
  //     }
  //     .el-input__inner {
  //       height: 100% !important;
  // }
  //   }
}
</style>
